home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / bin / coherence < prev    next >
Text File  |  2009-05-12  |  11KB  |  350 lines

  1. #! /usr/bin/python
  2. #
  3. # Licensed under the MIT license
  4. # http://opensource.org/licenses/mit-license.php
  5.  
  6. # Copyright 2006,2007,2008 Frank Scholz <coherence@beebits.net>
  7.  
  8. """ Coherence is a framework to host DLNA/UPnP devices
  9.  
  10.     For more information about it and its available backends
  11.     point your browser to: http://coherence.beebits.net
  12. """
  13.  
  14. import os, sys
  15.  
  16. import string
  17.  
  18. from twisted.python import usage, text
  19.  
  20.  
  21. from coherence import __version__
  22.  
  23. from coherence.extern.simple_config import Config,ConfigItem
  24.  
  25. """
  26.  thankfully taken from twisted.scripts._twistd_unix.py
  27. """
  28. def daemonize():
  29.     # See http://www.erlenstar.demon.co.uk/unix/faq_toc.html#TOC16
  30.     if os.fork():   # launch child and...
  31.         os._exit(0) # kill off parent
  32.     os.setsid()
  33.     if os.fork():   # launch child and...
  34.         os._exit(0) # kill off parent again.
  35.     os.umask(077)
  36.     null=os.open('/dev/null', os.O_RDWR)
  37.     for i in range(3):
  38.         try:
  39.             os.dup2(null, i)
  40.         except OSError, e:
  41.             if e.errno != errno.EBADF:
  42.                 raise
  43.     os.close(null)
  44.  
  45. """
  46.  taken with minor adjustments from twisted.python.text.py
  47. """
  48. def greedyWrap(inString, width=80):
  49.     """Given a string and a column width, return a list of lines.
  50.  
  51.     Caveat: I'm use a stupid greedy word-wrapping
  52.     algorythm.  I won't put two spaces at the end
  53.     of a sentence.  I don't do full justification.
  54.     And no, I've never even *heard* of hypenation.
  55.     """
  56.  
  57.     outLines = []
  58.  
  59.     #eww, evil hacks to allow paragraphs delimited by two \ns :(
  60.     if inString.find('\n\n') >= 0:
  61.         paragraphs = inString.split('\n\n')
  62.         for para in paragraphs:
  63.             outLines.extend(greedyWrap(para, width) + [''])
  64.         return outLines
  65.     inWords = inString.split()
  66.  
  67.     column = 0
  68.     ptr_line = 0
  69.     while inWords:
  70.         column = column + len(inWords[ptr_line])
  71.         ptr_line = ptr_line + 1
  72.  
  73.         if (column > width):
  74.             if ptr_line == 1:
  75.                 # This single word is too long, it will be the whole line.
  76.                 pass
  77.             else:
  78.                 # We've gone too far, stop the line one word back.
  79.                 ptr_line = ptr_line - 1
  80.             (l, inWords) = (inWords[0:ptr_line], inWords[ptr_line:])
  81.             outLines.append(string.join(l,' '))
  82.  
  83.             ptr_line = 0
  84.             column = 0
  85.         elif not (len(inWords) > ptr_line):
  86.             # Clean up the last bit.
  87.             outLines.append(' '.join(inWords))
  88.             del inWords[:]
  89.         else:
  90.             # Space
  91.             column = column + 1
  92.     # next word
  93.  
  94.     return outLines
  95.  
  96. """
  97.  taken with minor adjustments from twisted.python.usage.py
  98. """
  99. def docMakeChunks(optList, width=80):
  100.     """
  101.     Makes doc chunks for option declarations.
  102.  
  103.     Takes a list of dictionaries, each of which may have one or more
  104.     of the keys 'long', 'short', 'doc', 'default', 'optType'.
  105.  
  106.     Returns a list of strings.
  107.     The strings may be multiple lines,
  108.     all of them end with a newline.
  109.     """
  110.  
  111.     # XXX: sanity check to make sure we have a sane combination of keys.
  112.  
  113.     maxOptLen = 0
  114.     for opt in optList:
  115.         optLen = len(opt.get('long', ''))
  116.         if optLen:
  117.             if opt.get('optType', None) == "parameter":
  118.                 # these take up an extra character
  119.                 optLen = optLen + 1
  120.             maxOptLen = max(optLen, maxOptLen)
  121.  
  122.     colWidth1 = maxOptLen + len("  -s, --  ")
  123.     colWidth2 = width - colWidth1
  124.     # XXX - impose some sane minimum limit.
  125.     # Then if we don't have enough room for the option and the doc
  126.     # to share one line, they can take turns on alternating lines.
  127.  
  128.     colFiller1 = " " * colWidth1
  129.  
  130.     optChunks = []
  131.     seen = {}
  132.     for opt in optList:
  133.         if opt.get('short', None) in seen or opt.get('long', None) in seen:
  134.             continue
  135.         for x in opt.get('short', None), opt.get('long', None):
  136.             if x is not None:
  137.                 seen[x] = 1
  138.  
  139.         optLines = []
  140.         comma = " "
  141.         if opt.get('short', None):
  142.             short = "-%c" % (opt['short'],)
  143.         else:
  144.             short = ''
  145.  
  146.         if opt.get('long', None):
  147.             long = opt['long']
  148.             if opt.get("optType", None) == "parameter":
  149.                 long = long + '='
  150.  
  151.             long = "%-*s" % (maxOptLen, long)
  152.             if short:
  153.                 comma = ","
  154.         else:
  155.             long = " " * (maxOptLen + len('--'))
  156.  
  157.         if opt.get('optType', None) == 'command':
  158.             column1 = '    %s      ' % long
  159.         else:
  160.             column1 = "  %2s%c --%s  " % (short, comma, long)
  161.  
  162.         if opt.get('doc', ''):
  163.             doc = opt['doc'].strip()
  164.         else:
  165.             doc = ''
  166.  
  167.         if (opt.get("optType", None) == "parameter") \
  168.            and not (opt.get('default', None) is None):
  169.             doc = "%s [default: %s]" % (doc, opt['default'])
  170.  
  171.         if (opt.get("optType", None) == "parameter") \
  172.            and opt.get('dispatch', None) is not None:
  173.             d = opt['dispatch']
  174.             if isinstance(d, usage.CoerceParameter) and d.doc:
  175.                 doc = "%s. %s" % (doc, d.doc)
  176.  
  177.         if doc:
  178.             column2_l = greedyWrap(doc, colWidth2)
  179.         else:
  180.             column2_l = ['']
  181.  
  182.         optLines.append("%s%s\n" % (column1, column2_l.pop(0)))
  183.  
  184.         for line in column2_l:
  185.             optLines.append("%s%s\n" % (colFiller1, line))
  186.  
  187.         optChunks.append(''.join(optLines))
  188.  
  189.     return optChunks
  190.  
  191. usage.docMakeChunks = docMakeChunks
  192.  
  193. def setConfigFile():
  194.     def findConfigDir():
  195.         try:
  196.             configDir = os.path.expanduser('~')
  197.         except:
  198.             configDir = os.getcwd()
  199.         return configDir
  200.  
  201.     return os.path.join( findConfigDir(), '.coherence')
  202.  
  203.  
  204. class Options(usage.Options):
  205.  
  206.     optFlags = [['daemon','d', 'daemonize'],
  207.                 ['noconfig', None, 'ignore any configfile found'],
  208.                 ['version','v', 'print out version']
  209.                 ]
  210.     optParameters = [['configfile', 'c', setConfigFile(), 'configfile'],
  211.                      ['logfile', 'l', None, 'logfile'],
  212.                      ['option', 'o', None, 'activate option'],
  213.                      ['plugin', 'p', None, 'activate plugin'],
  214.                     ]
  215.  
  216.     def __init__(self):
  217.         usage.Options.__init__(self)
  218.         self['plugins'] = []
  219.         self['options'] = {}
  220.  
  221.     def opt_version(self):
  222.         print "Coherence version:", __version__
  223.         sys.exit(0)
  224.  
  225.     def opt_help(self):
  226.         sys.argv.remove('--help')
  227.         from coherence.base import Plugins
  228.         p = Plugins()
  229.         for opt,doc in self.docs.items():
  230.             if opt == 'plugin':
  231.                 self.docs[opt] = doc + '\n\nExample: --plugin=backend:FSStore,name:MyCoherence\n\nAvailable backends are:\n\n'
  232.                 self.docs[opt] += ', '.join(p.keys())
  233.  
  234.         print self.__str__()
  235.         sys.exit(0)
  236.  
  237.     def opt_plugin(self,option):
  238.         self['plugins'].append(option)
  239.  
  240.     def opt_option(self,option):
  241.         try:
  242.             key,value = option.split(':')
  243.             self['options'][key] = value
  244.         except:
  245.             pass
  246.  
  247. def main(config):
  248.  
  249.     from coherence.base import Coherence
  250.     c = Coherence(config)
  251.     #c = Coherence(plugins={'FSStore': {'content_directory':'tests/content'},
  252.     #                       'Player': {})
  253.     #c.add_plugin('FSStore', content_directory='tests/content', version=1)
  254.  
  255. if __name__ == '__main__':
  256.  
  257.     options = Options()
  258.     try:
  259.         options.parseOptions()
  260.     except usage.UsageError, errortext:
  261.         print '%s: %s' % (sys.argv[0], errortext)
  262.         print '%s: Try --help for usage details.' % (sys.argv[0])
  263.         sys.exit(0)
  264.  
  265.     if options['daemon'] == 1:
  266.         daemonize()
  267.  
  268.     config = {}
  269.  
  270.     if options['noconfig'] != 1:
  271.         try:
  272.             config = Config(options['configfile'],root='config').config
  273.         except SyntaxError:
  274.             import traceback
  275.             #print traceback.format_exc()
  276.             try:
  277.                 from configobj import ConfigObj
  278.                 config = ConfigObj(options['configfile'])
  279.             except:
  280.                 print "hmm, seems we are in trouble reading in any sort of config file"
  281.                 print traceback.format_exc()
  282.         except IOError:
  283.             print "no config file %r found" % options['configfile']
  284.             pass
  285.  
  286.     for k,v in options['options'].items():
  287.         config[k] = v
  288.  
  289.  
  290.     if options['logfile'] != None:
  291.         if isinstance(config,ConfigItem):
  292.             config['logging'] = {}
  293.             config['logging']['logfile'] = options['logfile']
  294.         else:
  295.             config['logfile'] = options['logfile']
  296.  
  297.     if options['daemon'] == 1:
  298.         if options['logfile'] == None:
  299.             if isinstance(config,ConfigItem):
  300.                 config.get('logging').get('level','none')
  301.             else:
  302.                 config.set('logmode','none')
  303.  
  304.     #print config
  305.  
  306.     if(config.get('use_dbus', 'no') == 'yes' or
  307.        config.get('glib', 'no') == 'yes' or
  308.        config.get('transcoding', 'no') == 'yes'):
  309.         try:
  310.             from twisted.internet import glib2reactor
  311.             glib2reactor.install()
  312.         except AssertionError:
  313.             print "error installing glib2reactor"
  314.  
  315.     if len(options['plugins']) > 0:
  316.         plugins = config.get('plugin')
  317.         if isinstance(plugins,dict):
  318.             config['plugin']=[plugins]
  319.         if plugins is None:
  320.             plugins = config.get('plugins',None)
  321.         if plugins == None:
  322.             config['plugin'] = []
  323.             plugins = config['plugin']
  324.  
  325.         while len(options['plugins']) > 0:
  326.             p = options['plugins'].pop()
  327.             plugin = {}
  328.             plugin_conf = p.split(',')
  329.             for pair in plugin_conf:
  330.                 pair = pair.split(':',1)
  331.                 if len(pair) == 2:
  332.                     pair[0] = pair[0].strip()
  333.                     if pair[0] in plugin:
  334.                         if not isinstance(plugin[pair[0]],list):
  335.                             new_list = [plugin[pair[0]]]
  336.                             plugin[pair[0]] = new_list
  337.                         plugin[pair[0]].append(pair[1])
  338.                     else:
  339.                         plugin[pair[0]] = pair[1]
  340.             try:
  341.                 plugins.append(plugin)
  342.             except AttributeError:
  343.                 print "mixing commandline plugins and configfile does not work with the old config file format"
  344.  
  345.  
  346.     from twisted.internet import reactor
  347.  
  348.     reactor.callWhenRunning(main, config)
  349.     reactor.run()
  350.